package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.ClinicsDao;
import dao.impl.ClinicsDaoImpl;
import entity.Clinics;
import utils.GetFieldUtils;
import utils.ResponseResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "ClinicsServlet", urlPatterns = "/bigProjects/ClinicsServlet")

public class ClinicsServlet extends HttpServlet {

    //获取所有诊疗类别:如普诊、急诊、感染病门诊……(无参数)
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ClinicsDao clinicsDao = new ClinicsDaoImpl();
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        List<String> list = clinicsDao.findAllClass();
        resp.getWriter().write(ResponseResult.success(list).toString());
    }

    //获得详细诊疗类别:急诊内科、骨科、儿科……(参数:department )
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ClinicsDao clinicsDao = new ClinicsDaoImpl();
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String depart = GetFieldUtils.getRequestPayload(req);
        ObjectMapper mapper = new ObjectMapper();
        Clinics clinics = mapper.readValue(depart, Clinics.class);

        List<String> list = clinicsDao.findAllDepartment(clinics.getDepartment());
        resp.getWriter().write(ResponseResult.success(list).toString());
    }

    //    新增一个类别(有两层:如"普诊"->"骨科" 两个都要输入)；参数    deClass   department
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ClinicsDao clinicsDao = new ClinicsDaoImpl();
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String str = GetFieldUtils.getRequestPayload(req);
        ObjectMapper mapper = new ObjectMapper();
        Clinics clinics = mapper.readValue(str, Clinics.class);

        int i = clinicsDao.insert(clinics);
        if (i > 1) resp.getWriter().write(ResponseResult.success().toString());
        else resp.getWriter().write(ResponseResult.failure("新增失败").toString());
    }
}
